package edu.mobbuzz.web.pages;

import java.util.ArrayList;
import java.util.List;

import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.Retain;
import org.apache.tapestry5.beaneditor.BeanModel;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.BeanModelSource;

import com.metamech.vorpal.UserIndex;

import edu.mobbuzz.daf.bean.User;
import edu.mobbuzz.web.base.SecureBasePage;
import edu.mobbuzz.web.facade.ManagementFacade;

public class UserGridPage extends SecureBasePage{
	
	private ManagementFacade managementFacade;
	
	private List<User> userList;
	@Property
	private User user;
	
	@Retain
	private BeanModel userModel;
	@Inject
	private BeanModelSource beanModelSource;
	@Inject
	private ComponentResources resources;
	@Component
	private Form userForm;
	
	private boolean delete;
	private List<String> deletedList;
	
	

	

	public boolean isDelete() {
		return delete;
	}
	
	public void setDelete(boolean delete) {
		if(delete){
			getDeletedList().add(user.getUsername());
		}
		this.delete = delete;
	}	
	
	public List<String> getDeletedList() {
		if(deletedList == null){
			deletedList = new ArrayList<String>();
		}
		return deletedList;
	}
	
	public ManagementFacade getManagementFacade() {
		if(managementFacade==null)
			managementFacade = new ManagementFacade();
		return managementFacade;
	}

	public BeanModel getUserModel() {
		return userModel;
	}	
	
	public List<User> getUserList() {
		if(userList==null){
			userList = new ArrayList<User>();
		}
		userList = getManagementFacade().getUserList("", "");		
		return userList;
	}

	public void setUserList(List<User> userList) {
		this.userList = userList;
	}
	
	void pageLoaded(){
		userModel = beanModelSource.createDisplayModel(User.class, resources.getMessages());
		userModel.add("actions",null).label("actions");
	
	}
	
	Object onSuccessFromUserForm(){		
		for(String element : getDeletedList()){
			user = (User)getManagementFacade().getUserByPrimaryKey(element);	
			if(user!=null)
				getManagementFacade().removeUser(user);
		}		
		return UserGridPage.class;
	}	
}
